/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package morseme;

import java.util.*;
import javax.microedition.lcdui.*;


/**
 *
 * @author craxidile
 */
public class BlindTextField extends TextField{

    private static final int KEY_WAIT = 800;
    private static final char SYMBOL = '5';
    
    private String prevString = "";
    private Timer inputTimer;
    private TimerTask inputTimerTask;
    private int symbolCount;
    private MorseME midlet;
    
    public BlindTextField(String label,String content,int length,int type,MorseME midlet){
        super(label,content,length,type);
        
        this.midlet = midlet;
        
        Timer stateTimer = new Timer();
        stateTimer.scheduleAtFixedRate(new TimerTask(){
            public void run(){
                int newLen = getString().length();
                int prevLen = prevString.length();
                
                if(newLen > prevLen){
                    fieldIncreased();                    
                }else if(newLen < prevLen){
                    fieldDecreased();
                }
                
                prevString = getString();
            }
        },0,100);
        
        
        this.inputTimer = new Timer();
    }
    
    private void symbolToNumber(){
        if(this.symbolCount == 0)
            return;
        
        StringBuffer result = new StringBuffer();
        String fieldString = getString();
        result.append(fieldString.substring(0,fieldString.length()-symbolCount));
        result.append(this.symbolCount % 10);
        this.symbolCount = 0;
        
        setString(result.toString());
        
        try{
            if(Option.SOUND_SEL == 0)
                this.midlet.play(110, 100);
            if(Option.VIBRATION_SEL == 0)
                this.midlet.vibrate(100);
            
            Thread.sleep(150);
            
            if(Option.SOUND_SEL == 0)
                this.midlet.play(110, 100);
            if(Option.VIBRATION_SEL == 0)
                this.midlet.vibrate(100);
        }catch(InterruptedException ie){}
    }
    
    public void fieldDecreased(){
        
    }
    
    public void fieldIncreased(){
        super.notifyStateChanged();
        
        if(Option.USER_TYPE != 0)
            return;
        
        if(this.inputTimerTask != null)
            this.inputTimerTask.cancel();
        
        String fieldStr = getString();
        if(fieldStr.charAt(fieldStr.length()-1) == SYMBOL){
            this.symbolCount++;
        }else{
            setString(fieldStr.substring(0,fieldStr.length()-1));
            return;
        }
        
        this.inputTimerTask = new TimerTask(){
            public void run(){
                symbolToNumber();
            }
        };
        this.inputTimer.schedule(this.inputTimerTask, KEY_WAIT);
    }
    
}






